<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\Common\Invitation;
use App\Models\System\Info;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Ofcold\IdentityCard\IdentityCard;

class BlogUserService
{

    use Service;

    /**
     * 用户首页展示
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function UserIndexService( $request )
    {
        $name       = $request->input('name');
        $static     = $request->input('static', '-1');
        $where      = function ( $query ) use ( $name, $static ) {
            if ( $name ) $query->where('name', 'like', '%' . $name . '%');
            if ( $static != '-1' ) $query->where('static', $static);
            $query->where('is_show', 2);
            $query->where('status', 1);
        };
        $with       = [
            'info'       => function ( $query ) {
                $query->select('uid', 'rename', 'username', 'card', 'content', 'avatar', 'constellation', 'github', 'sex',
                    'province', 'city', 'area', 'code', 'frequency', 'openid', 'birthday', 'zodiac');
                $query->with([
                    'provinceAll' => function ( $query ) {
                        $query->select('id', 'name');
                    },
                ]);
                $query->with([
                    'cityAll' => function ( $query ) {
                        $query->select('id', 'name');
                    },
                ]);
                $query->with([
                    'areaAll' => function ( $query ) {
                        $query->select('id', 'name');
                    },
                ]);
                $query->with([
                    'file' => function ( $query ) {
                        $query->select('id', 'url', 'file_url');
                    },
                ]);
            },
            'invitation' => function ( $query ) {
                $query->select('user_id', 'p_user_id');
                $query->with([
                    'pUser' => function ( $query ) {
                        $query->select('id', 'name');
                    },
                ]);
            },
        ];
        $select     = [ 'id', 'name', 'email', 'phone', 'is_show', 'static', 'created_at' ];
        $user       = User::PaginateModel($where, $with, $select);
        $invitation = new InvitationService();
        foreach ( $user as &$value ) {
            $value->invitationCount = $invitation->TreeChildCount($value->id, 0, TRUE);
            $value->team       = $invitation->TreeChildCount($value->id, 0, FALSE) + 1;
            $region            = '';
            if ( isset($value->info->provinceAll->name) ) {
                $region .= $value->info->provinceAll->name . '-';
            }
            if ( isset($value->info->cityAll->name) ) {
                $region .= $value->info->cityAll->name . '-';
            }
            if ( isset($value->info->areaAll->name) ) {
                $region .= $value->info->areaAll->name;
            }
            $region = ltrim($region, '-');
            $region = rtrim($region, '-');
            if ( ! $region ) $value->region = '暂无地址';
            else $value->region = $region;
            unset($value->info->provinceAll, $value->info->cityAll, $value->info->areaAll);
        }
        $user->appends([
            'name'   => $name,
            'static' => $static,
        ])->render();
        return view('blog.user.index', compact('user', 'request'));
    }


    /**
     * 创建用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserStoreService( $request )
    {
        $error     = $this->getErrorCode();
        $validator = $this->getAdminValidator()->BlogUserStoreValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        $json = Cookie::get('username_' . $request->input('submit'));//获取Cookie信息
        if ( ! $json ) return back()->with('error', $error::message(1030));
        $code = explode(',', $json);
        if ( $request->input('code') != $code[ 0 ] || Auth::id() != $code[ 2 ] ) return back()->with('error', $error::message(1021));
        if ( $request->input('email') != $code[ 1 ] ) return back()->with('error', $error::message(1022));
        if ( $request->input('card') ) {
            $idCard = IdentityCard::make($request->input('card'));
            if ( ! $idCard ) return back()->with('error', $error::message(2193));
            $birthday                 = new Carbon($idCard->getBirthday());
            $data1[ 'birthday' ]      = $idCard->getBirthday();
            $data1[ 'zodiac' ]        = $idCard->getZodiac();
            $data1[ 'constellation' ] = $idCard->getConstellation();
            $data1[ 'day' ]           = $birthday->day;
            $data1[ 'month' ]         = $birthday->month;
            $data1[ 'year' ]          = $birthday->year;
        }
        $data[ 'is_show' ]   = 2;
        $data[ 'password' ]  = bcrypt($request->input('password', 123456));
        $data[ 'name' ]      = $request->input('name');
        $data[ 'phone' ]     = $request->input('phone');
        $data[ 'email' ]     = $request->input('email');
        $user                = User::CreateModel($data);
        $data1[ 'uid' ]      = $user->id;
        $data1[ 'rename' ]   = $request->input('rename');
        $data1[ 'username' ] = $request->input('username');
        $data1[ 'card' ]     = $request->input('card');
        $data1[ 'content' ]  = $request->input('content');
        $data1[ 'province' ] = $request->input('province');
        $data1[ 'city' ]     = $request->input('city');
        $data1[ 'area' ]     = $request->input('area');
        $data1[ 'sex' ]      = $request->input('sex') ? : 1;
        $data1[ 'code' ]     = GetRandCode((int) config('page.GetRandCode'));
        $result              = DB::transaction(function () use ( $request, $error, $data1, $user ) {
            Info::CreateModel($data1);
            $data2[ 'user_id' ]   = $user->id;
            $data2[ 'p_user_id' ] = 0;
            if ( $request->filled('user_code') ) {
                $p_user = Info::ValueModel([ 'code' => $request->input('user_code') ], 'uid');
                if ( $p_user == $user->id ) return back()->with('error', $error::message(2208));
                $data2[ 'p_user_id' ] = $p_user;
            }
            Invitation::CreateModel($data2);
            return back()->with('success', $error::message(209));
        });
        return $result;
    }


    /**
     * 获取用户信息 编辑页面
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function UserEditService( $id )
    {
        $select = [ 'id', 'name', 'phone', 'email' ];
        $with   = [
            'info'       => function ( $query ) {
                $query->select('uid', 'rename', 'username', 'card', 'content', 'province', 'city', 'area', 'sex');
            },
            'invitation' => function ( $query ) {
                $query->select('p_user_id', 'user_id');
            },
        ];
        $user   = User::FindModel($id, $with, $select);
        return view('blog.user.edit', compact('user'));
    }


    /**
     * 更新用户信息
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserUpdateService( $request )
    {
        $error     = $this->getErrorCode();
        $validator = $this->getAdminValidator()->BlogUserUpdateValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        $user = User::FindModel($request->input('id'), [], [ 'id', 'email', 'phone' ]);
        if ( $request->input('email') != $user->email && $request->filled('email') ) {
            $json = Cookie::get('username_' . $request->input('submit'));//获取Cookie信息
            if ( ! $json ) return back()->with('error', $error::message(1030));
            $code = explode(',', $json);
            if ( $request->input('code') != $code[ 0 ] || Auth::id() != $code[ 2 ] ) return back()->with('error', $error::message(1021));
            if ( $request->input('email') != $code[ 1 ] ) return back()->with('error', $error::message(1022));
        }
        $data1[ 'birthday' ]      = NULL;
        $data1[ 'zodiac' ]        = NULL;
        $data1[ 'constellation' ] = NULL;
        $data1[ 'day' ]           = NULL;
        $data1[ 'month' ]         = NULL;
        $data1[ 'year' ]          = NULL;
        if ( $request->filled('card') and $request->input('card') != $user->info->card ) {
            $idCard = IdentityCard::make($request->input('card'));
            if ( ! $idCard ) return back()->with('error', $error::message(2193));
            $birthday                 = new Carbon($idCard->getBirthday());
            $data1[ 'birthday' ]      = $idCard->getBirthday();
            $data1[ 'zodiac' ]        = $idCard->getZodiac();
            $data1[ 'constellation' ] = $idCard->getConstellation();
            $data1[ 'day' ]           = $birthday->day;
            $data1[ 'month' ]         = $birthday->month;
            $data1[ 'year' ]          = $birthday->year;
        }
        $data[ 'is_show' ]  = 2;
        $data[ 'password' ] = bcrypt($request->input('password', 123456));
        $data[ 'phone' ]    = $request->input('phone');
        $data[ 'email' ]    = $request->input('email');
        $where              = function ( $query ) use ( $user ) {
            $query->where('id', $user->id);
            $query->where('is_show', 2);
        };
        $result             = DB::transaction(function () use ( $request, $where, $data, $user, $error ) {
            User::UpdateModel($where, $data);
            $data1[ 'uid' ]      = $user->id;
            $data1[ 'rename' ]   = $request->input('rename');
            $data1[ 'username' ] = $request->input('username');
            $data1[ 'card' ]     = $request->input('card');
            $data1[ 'content' ]  = $request->input('content');
            $data1[ 'province' ] = $request->input('province');
            $data1[ 'city' ]     = $request->input('city');
            $data1[ 'area' ]     = $request->input('area');
            $data1[ 'sex' ]      = $request->input('sex') ? : 1;
            Info::UpdateModel($user->id, $data1);
            return back()->with('success', $error::message(203));
        });
        return $result;
    }

    /**
     * 删除博客用户
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserDestroyService( $id )
    {
        $error = $this->getErrorCode();
        if ( $id == Auth::id() ) return back()->with('error', $error::message(1028));
        $user         = User::FindModel($id, [], [ 'id', 'static' ]);
        $user->status = 2;
        $user->save();
        return back()->with('success', $error::message(204));
    }


    /**
     * 批量删除 博客用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserDeleteService( $request )
    {
        $result = DB::transaction(function () use ( $request ) {
            $ids = $request->input('id');
            foreach ( $ids as $value ) {
                if ( $value == Auth::id() ) return message($this->getErrorCode()::message(1028));
                $user         = User::FindModel($value, [], [ 'id', 'static' ]);
                $user->static = 2;
                $user->save();
            }
            return data();
        });
        return $result;
    }

    /**
     * 禁用或启用 博客用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserStatusService( $request )
    {
        $id = $request->input('id');
        if ( $id == Auth::id() ) return message($this->getErrorCode()::message(1028));
        $data[ 'static' ] = $request->input('static') == 1 ? 2 : 1;//三元判断 用户的状态
        $where            = function ( $query ) use ( $id ) {
            $query->where('id', $id);
            $query->where('is_show', 2);
        };
        User::UpdateModel($where, $data);
        return data();
    }

}
